//
// Created by Astelaxy on 2023/11/22.
//
#include "tcpclient.h"
#include "string"

TCPClient::TCPClient() {
    WSAStartup(MAKEWORD(2, 2), &WsaData);
    Sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&SockAddr, 0, sizeof(SockAddr));
    memset(MsgBuffer, NULL, sizeof(char) * BUFFER_MAXBYTE);
    TimeOut = 1000;
}

TCPClient::~TCPClient() {
    TCP_Close();
}

bool TCPClient::TCP_Connect(std::string_view Ip, int Port) {
    SockAddr.sin_family = AF_INET;
    SockAddr.sin_port = htons(Port);
    SockAddr.sin_addr.s_addr = inet_addr(Ip.data());
    if (connect(Sock, (SOCKADDR *) &SockAddr, sizeof(SOCKADDR)) == SOCKET_ERROR) {
        int error = WSAGetLastError();
        WSACleanup();
        return false;
    }
    return true;
}

bool TCPClient::Send(std::string_view sv) {
    return send(Sock, sv.data(), sv.length(), NULL) == sv.length();
}

std::string TCPClient::Receive() {
    char szBuffer[BUFFER_MAXBYTE]{};
    recv(Sock, szBuffer, BUFFER_MAXBYTE, NULL);
    return std::string{szBuffer};
}

void TCPClient::TCP_Close() {
    closesocket(Sock);
    WSACleanup();
}

